package com.dictionary.hi;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.custom.tab.AbstractTabRootManager;
import com.custom.tab.AbstractViewController;
import com.inapp.util.BillingService;
import com.mango9x.utils.HttpHelpers;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewAnimator;

@SuppressLint("HandlerLeak")
public class FavoritesViewController extends AbstractViewController {

	public static final String KEY_FAVORITES_CHANGED = "KEY_FAVORITES_CHANGED";
	public static final String ADDED = "+";
	public static final String REMOVED = "-";

	private MainTabHostActivity mainTabHostActivity;
	private String[] imageUrlsSmall;
	private DisplayImageOptions options;
	private String[] imageUrlsBig;
	private String[] imageIds;
	private String[] likes;
	private String[] dislikes;
	private View v;
	private GridView gridView;
	private ViewAnimator mainViewAnimator;
	private TextView messageView;
	private ImageAdapter imageAdapter;
	private int gridImageWidth;
	private int gridImageHeight;
	private boolean favoritesChanged;

	public FavoritesViewController(AbstractTabRootManager tabRootManager,
			Bundle args) {
		super(tabRootManager, R.layout.vc_image_grid);
		try {
			mainTabHostActivity = (MainTabHostActivity) getActivity();
			gridImageWidth = (int) Math.ceil(mainTabHostActivity
					.getDisplyWidth() / 3.0);
			gridImageHeight = (65 * gridImageWidth) / 100;
			favoritesChanged = false;

			v = getView();
			mainViewAnimator = (ViewAnimator) v
					.findViewById(R.id.main_view_flipper);
			gridView = (GridView) v.findViewById(R.id.gridview);
			messageView = (TextView) v
					.findViewById(R.id.progress_message_text_view);
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.loading)
					.showImageForEmptyUri(R.drawable.ic_launcher)
					.cacheInMemory().cacheOnDisc().build();
			downloadandShowData();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void loadData() {
		try {
			List<int[]> favoriteImages = mainTabHostActivity
					.getDatabaseAccessor().getFavoriteImages();
			int idsInDB = favoriteImages.size();
			if (idsInDB > 0) {
				String ids = null;
				for (int i = 0; i < idsInDB; i++) {
					if (i == 0) {
						ids = Integer.toString(favoriteImages.get(i)[0]);
					} else {
						ids += "," + Integer.toString(favoriteImages.get(i)[0]);
					}
				}
				
				boolean isProVersion = BillingService.isPurchased(
						getSharedPreferences(), Extra.IN_APP_PRODUCT_ID)
						|| mainTabHostActivity.getPackageName().endsWith("pro");
				String url = isProVersion ? getString(R.string.images_info_url_pro)
						: getString(R.string.images_info_url);
				
				JSONObject json = HttpHelpers
						.getJSONfromURL(url + ids);
				JSONArray items = json.getJSONArray("images");
				int len = items.length();
				imageIds = new String[len];
				imageUrlsSmall = new String[len];
				imageUrlsBig = new String[len];
				likes = new String[len];
				dislikes = new String[len];
				if (len > 0) {
					for (int i = 0; i < len; i++) {
						JSONArray e = items.getJSONArray(i);
						imageIds[i] = e.getString(0);
						imageUrlsBig[i] = e.getString(1);
						imageUrlsSmall[i] = e.getString(2);
						likes[i] = e.getString(3);
						dislikes[i] = e.getString(4);

					}
				}
			} else {
				imageIds = new String[0];
				imageUrlsSmall = new String[0];
				imageUrlsBig = new String[0];
				likes = new String[0];
				dislikes = new String[0];
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (favoritesChanged) {
			favoritesChanged = false;
			downloadandShowData();
		}
	}

	@Override
	public void broadcastMessageReceived(String key, String message) {
		try {
			if (KEY_FAVORITES_CHANGED.equals(key)) {
				favoritesChanged = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void downloadandShowData() {
		new AsyncTask<String, String, String>() {
			protected void onPreExecute() {
				try {
					favoritesChanged = false;
					messageView.setText(R.string.loading);
					mainViewAnimator.setDisplayedChild(0);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			protected String doInBackground(String... arg0) {
				try {
					loadData();

				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(String unused) {
				try {

					imageAdapter = new ImageAdapter(getActivity());
					gridView.setAdapter(imageAdapter);
					gridView.setOnItemClickListener(new OnItemClickListener() {
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							startImageGalleryActivity(position);
						}
					});
					mainViewAnimator.setDisplayedChild(1);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute();
	}

	public void onDestroy() {
		try {
			mainTabHostActivity.getImageLoader().stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	private void startImageGalleryActivity(int position) {
		Bundle bundle = new Bundle();
		bundle.putStringArray(Extra.IMAGE_IDS, imageIds);
		bundle.putStringArray(Extra.IMAGES, imageUrlsBig);
		bundle.putStringArray(Extra.LIKES, likes);
		bundle.putStringArray(Extra.DISLIKES, dislikes);
		bundle.putInt(Extra.IMAGE_POSITION, position);
		pushViewController(new ImagePagerViewController(getTabRootManager(),
				bundle));
	}

	public class ImageAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public ImageAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return imageUrlsSmall.length;
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.item_grid_view, null);
				holder = new ViewHolder();
				holder.imageView = (ImageView) convertView
						.findViewById(R.id.image);
				holder.imageView.getLayoutParams().width = gridImageWidth;
				holder.imageView.getLayoutParams().height = gridImageHeight;

				convertView.setTag(holder);

			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			mainTabHostActivity.getImageLoader().displayImage(
					imageUrlsSmall[position], holder.imageView, options);
			return convertView;
		}

		class ViewHolder {
			ImageView imageView;
		}
	}
}